package com.peng.ppscalelibrary.BleManager.Manager;


import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.beacon.BeaconItem;
import com.inuker.bluetooth.library.model.BleGattCharacter;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.inuker.bluetooth.library.utils.ByteUtils;
import com.peng.ppscalelibrary.BleManager.Interface.BleConnectFliterInterface;
import com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel;
import com.peng.ppscalelibrary.BleManager.Model.BleDeviceModel;
import com.peng.ppscalelibrary.BleManager.util.BleUtil;

import java.util.List;

import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.CF367_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.ELECTRONIC_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.HEARTRATE_SCALE;

public class BleConnectFliterManager {

    private BleConnectFliterModel matchedFliterModel;

    private List<BleDeviceModel> bindingList;

    public void setBindingList(List<BleDeviceModel> bindingList) {
        this.bindingList = bindingList;
    }

    public boolean exceptBindedList2ConnectDevice(SearchResult resultDevice) {
        return filterByDeviceList(resultDevice, true);
    }

    public boolean inBindedList2ConnectDevice(SearchResult resultDevice) {
        return filterByDeviceList(resultDevice, false);
    }

    public boolean needNotConnect(SearchResult resultDevice) {
        if (!resultDevice.getName().equals(ELECTRONIC_SCALE) && !resultDevice.getName().equals(CF367_SCALE)) {
            return true;
        }
        return false;
    }

    public BleConnectFliterModel getMatchedFliterModel() {
        return matchedFliterModel;
    }

    public void monitorTargetResponse(int code, BleGattProfile profile, BleConnectFliterInterface fliterInterface) {
        BluetoothLog.d(String.format("profile----------------------:\n%s", profile));
        if (code == REQUEST_SUCCESS) {
            for (BleGattService service : profile.getServices()) {
                // 过滤service
                if (matchedFliterModel != null) {
                    if (service.getUUID().toString().startsWith(matchedFliterModel.getServiceUUID())) {
                        for (BleGattCharacter character : service.getCharacters()) {
                            // 过滤character
                            if (character.getUuid().toString().startsWith(matchedFliterModel.getCharacteristicNofifyUUID())) {
                                // 监听指定的nofity通道
                                if (fliterInterface != null) {
                                    fliterInterface.targetResponse(service.getUUID(), character.getUuid(), matchedFliterModel);
                                }
                            }
                            if (character.getUuid().toString().startsWith(matchedFliterModel.getCharacteristicWriteUUID())) {
                                // 监听指定的write通道
                                if (fliterInterface != null) {
                                    fliterInterface.target2Write(service.getUUID(), character.getUuid(), matchedFliterModel);
                                }
                            }

                        }
                    }
                }

            }
        }
    }

    public void monitirBMDJResponse(int code, BleGattProfile profile, BleConnectFliterInterface fliterInterface) {
        BluetoothLog.d(String.format("monitirBMDJResponse：profile----------------------:\n%s", profile));
        if (code == REQUEST_SUCCESS) {
            for (BleGattService service : profile.getServices()) {
                // 过滤service
                if (matchedFliterModel != null) {
                    if (service.getUUID().toString().startsWith(matchedFliterModel.getServiceUUID())) {
                        for (BleGattCharacter character : service.getCharacters()) {
                            // 过滤character
                            if (character.getUuid().toString().startsWith(matchedFliterModel.getCharacteristicBMDJUUID())) {
                                // 监听指定的nofity通道
                                if (fliterInterface != null) {
                                    BluetoothLog.d(String.format("service.getUUID()----------------------:%s\ncharacter.getUuid()----------------------:%s", service.getUUID(), character.getUuid()));
                                    fliterInterface.targetResponse(service.getUUID(), character.getUuid(), matchedFliterModel);
                                }
                            }
                        }
                    }
                }

            }
        }
    }

    private boolean filterByDeviceList(SearchResult device, boolean isBinding) {

        List<BleConnectFliterModel> fliterList = BleConnectFliterModel.getFliterArr();
        boolean isTarget = isTargetDevice(device, fliterList);
        if (isTarget) {
            return inBindedList(device, this.bindingList, isBinding);
        } else {
            return false;
        }

    }

    private boolean isTargetDevice(SearchResult device, List<BleConnectFliterModel> fliterList) {
        for (BleConnectFliterModel model : fliterList) {

            boolean equalName = equalNameWithCurrentFliterModel(device, model);
//            BluetoothLog.v("equalName----" + device.toString());
            if (equalName) {
                boolean equalBeaconBytesLenght = equalBeaconBytesLenghtWithCuurentFliterModel(device, model);
                BluetoothLog.v("equalBeaconBytesLenght----" + device.toString());

                if (equalBeaconBytesLenght) {
                    boolean equalAdvDataLength = equalAdvDataLengthWithCuurentFliterModel(device, model);
                    if (equalAdvDataLength) {
                        this.matchedFliterModel = model;
                        BluetoothLog.v("matchedFliterModel----" + model.toString());
                        return true;
                    }
                }

            }
        }
        return false;
    }

    private boolean equalNameWithCurrentFliterModel(SearchResult deviceModel, BleConnectFliterModel fliterModel) {
        if (deviceModel.getName().equals(fliterModel.getScaleName())) {
            return true;
        }
        return false;
    }

    private boolean equalAdvDataLengthWithCuurentFliterModel(SearchResult device, BleConnectFliterModel fliterModel) {

        Beacon beacon = new Beacon(device.scanRecord);
        for (BeaconItem beaconItem : beacon.mItems) {
            if (beaconItem.type == fliterModel.getAdvDataType()) {
                if (beaconItem.bytes.length == fliterModel.getAdvDataLength()) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean equalBeaconBytesLenghtWithCuurentFliterModel(SearchResult device, BleConnectFliterModel fliterModel) {
        Beacon beacon = new Beacon(device.scanRecord);
        String str = String.format("getName %s-----getAddress %s-----beacon %s----length %d", device.getName(), device.getAddress(), ByteUtils.byteToString(beacon.mBytes), ByteUtils.byteToString(beacon.mBytes).length());
        BluetoothLog.d(String.format("beacon----------------------:\n%s\n", str));
        if (ByteUtils.byteToString(beacon.mBytes).length() == fliterModel.getBeaconBytesLenght()) {
            return true;
        }
        return false;
    }

    private boolean inBindedList(SearchResult device, List<BleDeviceModel> deviceList, boolean isBinding) {
        BleDeviceModel currentDeviceModel = new BleDeviceModel(device.getAddress(), device.getName());
        if (isBinding) {
            for (BleDeviceModel deviceModel : deviceList) {
                if (deviceModel.getDeviceMac().equals(currentDeviceModel.getDeviceMac())) {
                    BluetoothLog.v("deviceModel----" + deviceModel.getDeviceMac());
                    BluetoothLog.v("currentDeviceModel----" + currentDeviceModel.getDeviceMac());
                    return false;
                }
            }
            BluetoothLog.v("currentDeviceModeltrue----" + currentDeviceModel.getDeviceMac());
            return true;
//            return !deviceList.contains(currentDeviceModel);
        } else {
            for (BleDeviceModel deviceModel : deviceList) {
                if (deviceModel.getDeviceMac().equals(currentDeviceModel.getDeviceMac())) {
                    return true;
                }
            }
            return false;
        }
    }

    public BleConnectFliterModel getTargetDevice(SearchResult device) {

        for (BleConnectFliterModel model : BleConnectFliterModel.getFliterArr()) {

            boolean equalName = equalNameWithCurrentFliterModel(device, model);
//            BluetoothLog.v("equalName----" + device.toString());
            if (equalName) {
                boolean equalBeaconBytesLenght = equalBeaconBytesLenghtWithCuurentFliterModel(device, model);
                BluetoothLog.v("equalBeaconBytesLenght----" + device.toString());

                if (equalBeaconBytesLenght) {
                    boolean equalAdvDataLength = equalAdvDataLengthWithCuurentFliterModel(device, model);
                    if (equalAdvDataLength) {
                        this.matchedFliterModel = model;
                        BluetoothLog.v("matchedFliterModel----" + model.toString());
                        return matchedFliterModel;
                    }
                }

            }
        }
        return matchedFliterModel;
    }



}
